package cn.itcast.gateway.filter;


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class LoginFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取请求参数
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        //2 获取authorization参数
        String authorization = queryParams.getFirst("authorization");
        //3 判断是否正确
        if ("admin".equals(authorization)){
            //4 正确则放行
            return chain.filter(exchange);
        }
        //5 错误则进行拦截
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);   //返回状态码401 没有权限
        return exchange.getResponse().setComplete();      //处理结果
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;    //返回order最优先
    }
}
